package svc

import (
	"mydemo/rpc/user/internal/config"

	"github.com/zeromicro/go-zero/core/stores/redis"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type ServiceContext struct {
	Config config.Config
	Db     *gorm.DB
	Redis  *redis.Redis
}

func NewServiceContext(c config.Config) *ServiceContext {

	db, err := gorm.Open(mysql.Open(c.Mysql.Datasource), &gorm.Config{})
	if err != nil {
		return nil
	}
	// 打印出对应的sql
	db.Logger = logger.Default.LogMode(logger.Info)
	newRedis := redis.New(c.Redis.Host, redisConfig(c))
	return &ServiceContext{
		Config: c,
		Db:     db,
		Redis:  newRedis,
	}
}

func redisConfig(c config.Config) redis.Option {
	return func(r *redis.Redis) {
		r.Type = redis.NodeType
		r.Pass = c.Redis.Pass
	}
}
